package vno.fux.task
{
	import vno.fux.ui.UiLayer;

	public class TaskSystem
	{
		private static var instance:TaskSystem;
		private var _switches:Array;
		private var _tasks:Object;
//		private var _cndi:ConditionInterpreter;
//		private var _cmdi:CommandInterpreter;
		public function TaskSystem(script:String, pvt:PrivateClass)
		{
			_switches = [];
			_tasks = {};
			CommandInterpreter.setSwitches(_switches);
			ConditionInterpreter.setSwitches(_switches);
			
			var filtEmptyStr:Function = 
				function(item:*, index:int, array:Array):Boolean
				{
					return item != "";
				};
			var taskar:Array = script.split("{\n").filter(filtEmptyStr);
			for each(var taskStr:String in taskar)
			{
				var segments:Array = taskStr.split("\n").filter(filtEmptyStr);
				var npc:int = int(segments[0].split(" ")[1]);
				var tasktmp:Task = new Task;
				_tasks[npc] = tasktmp;
				var i:int = 0;
				while(segments[++i]!="}")
				{
					var pageNum:int = int(segments[i].split(" ")[1]);
					tasktmp.addPage(pageNum);
					var page:TaskPage = tasktmp.getPage(pageNum);
					var conditions:Array = page.conditions;
					for(i = i+2;segments[i]!="-end";i++)
					{
						conditions.push(segments[i].replace("\t",""));
					}
					var commands:Array = page.commands;
					for(i = i+2;segments[i]!="-end";i++)
					{
						commands.push(segments[i].replace("\t",""));							
					}
				}
			}
		}
		public function doTask(index:int):void
		{
			if(!(_tasks[index] as Task)) return;
			var commands:Array = (_tasks[index] as Task).getVailidPage().commands;
			for(var j:int=0;j<commands.length;j++)
			{
				var tmp:Array = commands[j].split(": ");
				var command:String = tmp[0];
				var params:String = tmp[1];
				CommandInterpreter[command](params);
			}
		}
		public function switchOn(id:uint):void
		{
			_switches[id]=true;
		}
		public static function init(script:String):void
		{
			if(TaskSystem.instance)
			{
				throw new Error("You can't init the TaskSystem twice!")
			}
			TaskSystem.instance = new TaskSystem(script, new PrivateClass);
		}
		public static function getInstance():TaskSystem
		{
			return TaskSystem.instance;
		}
		
		public function setUi(param0:UiLayer):void
		{
			CommandInterpreter.ui = param0;
		}
	}
}
class PrivateClass
{
	public function PrivateClass()
	{
	}
}